package com.wyh.yuhcloud.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wyh
 * @version 1.0
 * @date 2021/10/4 18:12
 */
@Component
@Slf4j
public class TokenLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    //退出登录 不从这走
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //获取token
        String token = request.getHeader("Authorization");
        //判断token是否为空,移除token,从redis中删除token
        if (token!=null) {
            String username = tokenManager.getUserInfoFromToken(token);
            redisTemplate.delete(username);
            log.info("用户注销："+token);
        }
        ResponseUtil.out(response, R.ok());
    }
}
